package com.humanminoritygame.web.exceptionresolvers;

import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.humanminoritygame.web.exception.EmailNotificationService;
import com.humanminoritygame.web.exception.NotificationService;

public class NotifyingExceptionResolver extends  SimpleMappingExceptionResolver {
  private Properties priorityExpMappings;
  private Map priorityNSMappings;
  private String notificationMessage = null;

 // private Log log = LogFactory.getLog(NotifyingExceptionResolver.class);
  
  public void setPriorityExceptionMappings(Properties  priorityExpMappings){
    this.priorityExpMappings = priorityExpMappings;
  }

  public void setPriorityNotificationServicesMappings (Map priorityNSMappings){
    this.priorityNSMappings = priorityNSMappings;
  }

  public void setNotificationMessage(String message){
    this.notificationMessage = message;
  }

  protected ModelAndView doResolveException(HttpServletRequest request,  HttpServletResponse response, Object handler, Exception ex) {
    //log.warn("An Exception has occured in the application", ex);
    sendNotification(ex);
    return super.doResolveException(request, response, handler, ex);
  }

  private void sendNotification(Exception ex) {
    String priority = resolvePriority(this.priorityExpMappings, ex);
    NotificationService notificationService = resolveNotificationService (this.priorityNSMappings, priority);
    String message = (notificationMessage == null ? priority :  notificationMessage);

    if(notificationService != null) {
      //log.debug("notification message was sent");
     // System.out.println("llamo a notification.send");
      notificationService.sendNotification(message, ex);
    }
  }

  private String resolvePriority(Properties priorityExpMappings,  Exception ex){
    return this.findMatchingViewName(priorityExpMappings, ex);
  }

  private NotificationService resolveNotificationService (Map priorityNSMappings, String priority){
    NotificationService notificationService = null;
    notificationService = (NotificationService) priorityNSMappings.get(priority);
  //  System.out.println("resolveNotificationService priority-----> "+priority);
   // System.out.println("resolveNotificationService -----> "+notificationService);
    if (notificationService != null && logger.isDebugEnabled()) {
      logger.debug("Resolving to a notification service for priority ["  + priority + "]");
    }
    return notificationService;
  }
}
